package 极客时间.concurrence.并发编程实战篇.信号量模型;

import java.awt.*;
import java.util.Vector;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.LockSupport;

import static java.util.concurrent.TimeUnit.SECONDS;

/**
 * @Author idea
 * @Date created in 8:39 上午 2020/7/24
 */
public class ResourcePools {

    private int size;

    private static Semaphore semaphore;

    /**
     * 模拟数据库的连接
     */
    private class Connection {
        private String url;
        private String password;
    }

    private static Vector<Connection> resourcePool = new Vector<>();

    public ResourcePools(int size) {
        synchronized (ResourcePools.class){
            for (int i = 0; i < size; i++) {
                Connection connection = new Connection();
                connection.url = "jdbc://test.db.xxx";
                connection.password = "root@dbpass";
                resourcePool.add(connection);
            }
            semaphore = new Semaphore(size);
        }
    }

    /**
     * 尝试获取连接
     * @return
     */
    public Connection getConnection(){
        Connection connection = null;
        try {
            semaphore.tryAcquire(10, SECONDS);
            connection = resourcePool.remove(0);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            semaphore.release();
        }
        return connection;
    }

    public void useConnection(){
        System.out.println("使用连接处理某些业务场景");
        long end = System.currentTimeMillis()+1000;
        LockSupport.parkUntil(end);
    }



}
